var detafeed_historyTime = 0
var detafeed_lastResolution = null
var detafeed_lastSymbol = null
var t_init = null;
var r_data;
var urls1 = "https://line.dupont-ex.com/getdatahis.ashx"//前三个币的分时线
var urls2 = "https://days.dupont-ex.com/quotations/getKlineDataByIntervalTimeForHttp"//前三个币的日线
var urls3 = "https://days.dupont-ex.com/quotations/getKlineDataByIntervalTimeForHttpTemp"//后两个币的全部
var urls;
var status;

function callbackparam(res) {
}
// var eosFormatTime2 = function (oldTimes1) {
//     var time1 = oldTimes1.split(' ')[0];
//     var arrTime = oldTimes1.split(' ')[1].split(':');
//     var time2 = arrTime.slice(1, arrTime.length).join(':');
//     var h = parseInt(arrTime[0]) + 8;
//     var newH = ((h < 24) ? h : (h % 24)).toString();
//     return time1 + ' ' + newH + ':' + time2;
// }
var eosFormatTime2 = function (oldTimes1) {
    var miao = 8*60*60*1000
    var miao2 = new Date(oldTimes1).getTime()
    return miao + miao2
}
function types(dataList) {
    var newList = dataList.data
    for (var i = 0; i < dataList.min.length; i++) {
        newList[i].push(dataList.min[i])
    }
    var list = []
    for (var i = 0; i < newList.length; i++) {
        var aa = {}
        // aa.time = new Date(eosFormatTime2(newList[i][4])).getTime()
        // aa.priceTime = eosFormatTime2(newList[i][4])
        aa.time = eosFormatTime2(newList[i][4])
        aa.priceTime =new Date(eosFormatTime2(newList[i][4]))
        aa.maxPrice = newList[i][3]
        aa.minPrice = newList[i][2]
        aa.closePrice = newList[i][1]
        aa.openPrice = newList[i][0]
        list.push(aa)
    }
    return list
}
var datafeed = {
    getApiTime: (resolution) => {
        switch (resolution) {
            case '1':
                return '1min'
            case '3':
                return '3min'
            case '5':
                return '5min'
            case '15':
                return '15min'
            case '30':
                return '30min'
            case '60':
                return '60min'
            case '240':
                return '4h'
            case 'D':
                return '1day'
            default:
                return '15m'
        }
    },
    getSendSymbolName: (symbolName, index) => {
        var name = symbolName.split('/');
        return (name[index]).toLocaleUpperCase()
    },
    onReady: (callback) => {
        console.log("=====onReady running");
        callback()
    },
    resolveSymbol: (symbolName, onSymbolResolvedCallback, onResolveErrorCallback) => {
        var symbol_stub = {
            name: symbolName,
            description: "",
            has_intraday: true,
            has_no_volume: false,
            minmov: 1,
            minmov2: 2,
            pricescale: 100,
            session: "24x7",
            supported_resolutions: ["1", "5", "15", "30", "60", "D"],
            ticker: symbolName,
            timezone: "Asia/Shanghai",
            type: "stock"
        }
        setTimeout(() => onSymbolResolvedCallback(symbol_stub), 0);
    },
    getBars: function (symbolInfo, resolution, from, to, onHistoryCallback, onErrorCallback, firstDataRequest) {
        if (!detafeed_historyTime || (resolution !== detafeed_lastResolution) || detafeed_lastSymbol !== symbolInfo.name) {   // 储存请求过的产品 
            detafeed_lastSymbol = symbolInfo.name   // 记录目前时间搓，就用目前的目前时间搓往前请求历史数据    
            detafeed_historyTime = Date.now()
        }
        clearInterval(t_init)
        console.log(symbolInfo.name,6363)
        const e_time = Number((Date.now() + '').substr(0, 9) + '0000');
        if(symbolInfo.name=="BTC/USDT" || symbolInfo.name=="ETH/USDT" || symbolInfo.name=="LTC/USDT" ){
            if(resolution == "D"){
                r_data = {
                    min: "1day",
                    symbol: this.getSendSymbolName(symbolInfo.name, 0) + this.getSendSymbolName(symbolInfo.name, 1),
                    type: 'stock'
                }
                urls = urls2
                status = "json"
            }else{
                r_data = {
                    min: resolution,
                    symbol: this.getSendSymbolName(symbolInfo.name, 0) + this.getSendSymbolName(symbolInfo.name, 1),
                    type: 'stock'
                }
                urls = urls1
                status = "jsonp"
            }
           
        }else if(symbolInfo.name=="HS300/USDT" || symbolInfo.name=="IC500/USDT"){
            r_data = {
                min: resolution=="D"?"1day":resolution+"min",
                symbol: this.getSendSymbolName(symbolInfo.name, 0) + this.getSendSymbolName(symbolInfo.name, 1),
                type: 'stock'
            }
            urls = urls3
            status = "json"
        }
        
        $.ajax({
            type: 'GET',
            url: urls,
            contentType: 'application/json',
            data: r_data,
            async: false,
            dataType: status,
            jsonp: "callbackparam",
            success: function (data) {
                if (data.data && Array.isArray(data.data)) {     // 记录这次请求的时间周期    
                    const k_list = types(data);
                    console.log(k_list)
                    detafeed_lastResolution = resolution;
                    var meta = { noData: true };
                    var bars = []
                    if (k_list.length) {
                        localStorage.setItem('k_open', Number(k_list[k_list.length - 1].openPrice))
                        localStorage.setItem('k_high', Number(k_list[k_list.length - 1].maxPrice))
                        localStorage.setItem('k_low', Number(k_list[k_list.length - 1].minPrice))
                        localStorage.setItem('k_close', Number(k_list[k_list.length - 1].closePrice))
                        localStorage.setItem('k_time', k_list[k_list.length - 1].priceTime);
                        detafeed_historyTime = e_time;
                        for (var i = 0; i < k_list.length; i++) { bars.push({ time: k_list[i].time * 1, close: k_list[i].closePrice, open: k_list[i].openPrice, high: k_list[i].maxPrice, low: k_list[i].minPrice }) }
                        meta = { noData: true }
                    } else { meta = { noData: true } }
                    onHistoryCallback(bars, meta);
                }

            },
            onErrorCallback: function (message) { console.log(message) }
        })
    },
    subscribeBars: function (symbolInfo, resolution, onRealtimeCallback, subscribeUID, onResetCacheNeededCallback) {
        t_init = setInterval(() => {
            const e_time = Number((Date.now() + '').substr(0, 9) + '0000')
            // const r_data = {
            //     min: resolution == "D" ? "1day" : resolution,
            //     symbol: this.getSendSymbolName(symbolInfo.name, 0) + this.getSendSymbolName(symbolInfo.name, 1),
            //     type: 'stock'
            // }
            if(symbolInfo.name=="BTC/USDT" || symbolInfo.name=="ETH/USDT" || symbolInfo.name=="LTC/USDT" ){
                if(resolution == "D"){
                    r_data = {
                        min: "1day",
                        symbol: this.getSendSymbolName(symbolInfo.name, 0) + this.getSendSymbolName(symbolInfo.name, 1),
                        type: 'stock'
                    }
                    urls = urls2
                    status = "json"
                }else{
                    r_data = {
                        min: resolution,
                        symbol: this.getSendSymbolName(symbolInfo.name, 0) + this.getSendSymbolName(symbolInfo.name, 1),
                        type: 'stock'
                    }
                    urls = urls1
                    status = "jsonp"
                }
               
            }else if(symbolInfo.name=="HS300/USDT" || symbolInfo.name=="IC500/USDT"){
                r_data = {
                    min: resolution=="D"?"1day":resolution+"min",
                    symbol: this.getSendSymbolName(symbolInfo.name, 0) + this.getSendSymbolName(symbolInfo.name, 1),
                    type: 'stock'
                }
                urls = urls3
                status = "json"
            }
            $.ajax({
                type: 'GET',
                url:  urls,
                contentType: 'application/json',
                data: r_data,
                async: false,
                dataType:status,
                jsonp: "callbackparam",
                success: function (data) {
                    if (data.data && Array.isArray(data.data)) {     // 记录这次请求的时间周期    
                        const k_list = types(data);
                        k_list.reverse();
                        if (k_list.length) {
                            detafeed_historyTime = e_time;
                            if (localStorage.k_time == k_list[0].priceTime) {
                                for (var i = 0; i < 1; i++) {
                                    onRealtimeCallback({
                                        time: Number(k_list[i].time),
                                        close: k_list[i].closePrice,
                                        open: k_list[i].openPrice,
                                        high: k_list[i].maxPrice,
                                        low: k_list[i].minPrice,
                                    })
                                }
                            } else {
                                for (var i = 0; i < k_list.length; i++) {
                                    onRealtimeCallback({
                                        time: Number(k_list[i].time),
                                        close: k_list[i].closePrice,
                                        open: k_list[i].openPrice,
                                        high: k_list[i].maxPrice,
                                        low: k_list[i].minPrice,
                                    })
                                }
                            }
                            localStorage.setItem('k_time', k_list[0].priceTime);
                        }
                    }
                },
                onErrorCallback: function (message) { console.log(message) }
            })
        }, 10000)
    },

}